<script setup lang="ts">
import { BookRequestParams, RequestParams } from "@/api/bookshelfToChina/type";
import {
  bookList,
  addbook,
  delbook,
  Formbook,
  LibraryOptions,
  updatebook,
  importBook,
} from "@/api/bookshelfToChina/index.ts";

import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
// ================================================================================
// ref
const queryFormRef = ref(); //搜索
const ruleFormRef = ref(); //弹框表单

const ids = ref([] as number[]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
let LibOptions = ref([] as any);
const ruleForm = ref({} as any);
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
} as RequestParams);
const tableList = ref([{}] as BookRequestParams[]);

const rules = reactive({
  shelfName: [{ required: true, message: "书架名称不能为空", trigger: "blur" }],
  chinaClass: [
    { required: true, message: "中图法规则不能为空", trigger: "blur" },
  ],
  libraryId: [{ required: true, message: "请选择图书馆", trigger: "change" }],
});
// 挂载
onMounted(() => {
  handleQuery();
});
// ================================================================================

/**
 * 查询
 */

const handleQuery = async () => {
  try {
    loading.value = true;
    const res = await bookList(queryParams);
    console.log(res, "res列表");

    tableList.value = res.data.records;

    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    // console.error(error);
    loading.value = false; // 将 loading 的值设置为 false，以便停止加载动画
  }
};
/**
 * 重置
 */

const resetQuery = () => {
  queryParams = {} as any;
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  handleQuery();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */
const openDialog = async (id?: number) => {
  dialogVisible.value = true;
  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;
  // console.log(LibOptions.value, "LibOptions图书下拉");

  if (id) {
    const res = await Formbook(id as any);
    ruleForm.value = res.data;
    // console.log(res, "addFormUser");
    title.value = "修改书架";
  } else {
    title.value = "新增书架";

    if (ruleFormRef.value) {
      ruleFormRef.value.clearValidate();
    }
    ruleForm.value = {};
  }
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleForm.value = {} as any;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = ruleForm.value.id;
      loading.value = true;
      if (userId) {
        // console.log(ruleForm.value, "编辑");
        updatebook(ruleForm.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("图书修改成功");
              close();
              handleQuery();
            } else {
              ElMessage.error(res.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        //  console.log("新增");
        addbook(ruleForm.value)
          .then((res) => {
            if (res.code == 200) {
              ElMessage.success("图书新增成功");
              close();
              handleQuery();
            } else {
              ElMessage.error(res.msg);
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
};

/**
 * 删除
 */
const dell = (id: any) => {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // console.log(Number(userIds), userIds);
    delbook(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        handleQuery();
      }
    });
  });
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;

  handleQuery();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};

// -----------------------------------------------------------------
// 修改上下架状态

const FormRef = ref();
const Formrule = ref({} as any);
const dialog = ref(false);

const booklibraryId = ref(null as any);
const bookLocationItem = ref(null as any); // 创建一个ref引用
const clearBookLocationValidation = () => {
  bookLocationItem.value.clearValidate(); // 调用clearValidate方法清除校验状态
  booklibraryId.value.clearValidate();
};

// -----------------------------------------------------------------

// 导入

const fileRef = ref();

// 在组件中定义状态变量
const iptmarker = () => {
  fileRef.value.click();
};
const handleFileChange = async (e: any) => {
  const MAX_SIZE = 10 * 1024 * 1024;
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件大小
  if (file.size > MAX_SIZE) {
    alert("文件大小不能超过10MB！");
    return;
  }

  // 验证文件类型
  const allowedExtensions = ["xlsx", "xls"];
  const fileExtension = file.name.split(".").pop().toLowerCase();
  if (!allowedExtensions.includes(fileExtension)) {
    alert("请上传 Excel 文件！");
    return;
  }

  const load = ElLoading.service({
    lock: true,
    text: "正在导入，请稍候...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    // 模拟耗时操作（实际替换为你的导入逻辑）
    await new Promise((resolve) => setTimeout(resolve, 2000));
    const res = await importBook(file);
    // 导入成功提示
    ElMessage.success(res.msg);
    fileRef.value.value = null;
    handleQuery(); // 刷新数据
    load.close();
  } catch (error) {
    load.close();
    // 导入失败提示
    //console.log(error);
    //ElMessage.info("导入中请耐心等待不要重复导入");
  } finally {
    // 无论成功失败，最后清理状态
    load.close();
    handleQuery(); // 刷新数据
    // 清空文件输入
  }
};

// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize;
};
const isSearchDisabled = computed(() => {
  return !queryParams.bookCode && !queryParams.keyword;
});
</script>

<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="550px"
      append-to-body
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <!-- <el-form-item label="图书馆" prop="libraryId">
          <el-select
            v-model="ruleForm.libraryId"
            placeholder="请选择图书馆"
            style="width: 350px"
          >
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="书架名称" prop="shelfName">
          <el-input
            style="width: 350px"
            v-model="ruleForm.shelfName"
            placeholder="请输入书架名称"
          />
        </el-form-item>
        <el-form-item label="中图法规则" prop="chinaClass">
          <el-input
            style="width: 350px"
            v-model="ruleForm.chinaClass"
            placeholder="请输入中图法规则"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="书架名称" prop="name">
          <el-input
            v-model="queryParams.shelfName"
            placeholder="书架名称查询"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="中图法规则" prop="name">
          <el-input
            v-model="queryParams.chinaClass"
            placeholder="中图法规则查询"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="Search"
            >搜索</el-button
          >
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div>
            <el-button icon="Plus" type="success" @click="openDialog()"
              >新增</el-button
            >
            <!--    :disabled="isSearchDisabled" -->

            <input
              ref="fileRef"
              type="file"
              style="display: none"
              @change="handleFileChange"
            />
            <el-button
              type="warning"
              style="margin-left: 10px"
              icon="Top"
              @click="iptmarker"
              >图书导入</el-button
            >
          </div>
          <div></div>
        </div>

        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="Delete"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          width="65"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <!--  <el-table-column type="selection" width="55" align="center" /> > -->
        <el-table-column label="书架名称" prop="shelfName" align="center" />

        <el-table-column label="中图法规则" prop="chinaClass" align="center" />

        <!-- <el-table-column label="图书状态" prop="bookStatus" :align="'center'">
          <template #default="{ row }">
            {{ getbooksStatus(row.bookStatus) }}
          </template>
        </el-table-column> -->

        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="160px"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog(row.id)"
              >编辑</el-button
            >
            <el-button type="primary" link size="small" @click="dell(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
